package com.cloudservice.ccs.config;

import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        Map<String, String> map = new LinkedHashMap<>();
        // map.put("/login", "anon");
        // map.put("/**", "authc");
        map.put("/**", "anon");
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        // login url 配置有误，前后端分离的结构中不应后端提供自动跳转 (?)
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("");
        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(customerServiceRealm());
        return securityManager;
    }

    @Bean
    public CustomerServiceRealm customerServiceRealm() {
        CustomerServiceRealm customerServiceRealm = new CustomerServiceRealm();
        customerServiceRealm.setCredentialsMatcher(new BcryptCredentialsMatcher());
        return customerServiceRealm;
    }
}
